import React, { useEffect, useRef, useContext, useState, useCallback, useMemo } from 'react';
import { ScrollView, Dimensions, Image, ImageBackground, Text, TextInput, TouchableOpacity, View, Alert, NativeModules } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import DateTimePickerModal from "react-native-modal-datetime-picker";
import { loadAppConfig, saveAppConfig } from '../util/StorageUtil';
const NAModule = NativeModules.NAModule;

const width = Dimensions.get('window').width
const height = Dimensions.get('window').height
const artImgWidth = width / 2;
const artImgHeight = artImgWidth * 124 / 510
const mTop = height / 5

const createStyles = () =>
    StyleSheet.create({
        item: {
            backgroundColor: "#fafafa",
            margin: 8,
            marginHorizontal: 10,
            borderRadius: 20,
            // flex: 1,
            height: 45,
            width: '100%',
            borderColor: '#ddd',
            paddingHorizontal: 20,
            alignItems: 'center',
            alignContent: 'center'
        }
    });

export const Naming = (props) => {
    const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
    const [birthDay, setBirthDay] = useState(null);
    const [isTimePickerVisible, setTimePickerVisibility] = useState(false);
    const [birthDate, setBirthDate] = useState("");
    const [birthTime, setBirthTime] = useState("");
    const [sex, setSex] = useState("男");
    const [isDoubleWord, setIsDoubleWord] = useState(true);
    const [isMore, setIsMore] = useState(false);

    const [name, setName] = useState("");
    const [birthPlace, setBirthPlace] = useState("");

    // const [birthDay, setBirthDay] = useState(null);
    const birthDayRef = useRef(null)

    useEffect(() => {
        loadAppConfig().then((res) => {
            if (res) {
                global.AppConfig = res
            }

        }).catch((err) => {
            console.log('loadAppConfig err', err);
        })
        fetch("https://semperchen.github.io/qmcz/test.json")
            .then((response) => {
                return response.json()
            })
            .then((responseData) => {

                console.log('responseData', responseData);
                NAModule.setAdData(responseData)
            }).catch((error) => {
                console.warn("error", error)
            });
        // fetch("http://27.102.66.201:8080/api/create_name", {
        //     method: "POST",
        //     headers: {
        //         "content-type": "application/json"
        //     },
        //     body: JSON.stringify({
        //         "x": "李",
        //         "xb": "男",
        //         "csrq": "2023年3月19日 17点55分",
        //         "csdd": "广东省深圳市",
        //         "jy": "",
        //         "zs": 3
        //     })
        // })
        //     .then((response) => {
        //         return response.json()
        //     })
        //     .catch((error) => {
        //         console.warn("error", error)
        //     }).then((responseData) => {

        //         console.warn("responseData", responseData);
        //     }).done();
        

        // NAModule.setAdData({
        //     "gDTAppId": "1105344611",
        //     "gDTInterstitialAdId": "1050652855580392",
        //     "gDTVideoAdId": "8020744212936426",
        //     "cSJAppId": "5446504",
        //     "cSJVideoAdId": "102525233",
        //     "cSJInterstitialAdId": "102525232",
        //     "isShowGDTVideoAd": false,
        //     "isShowCSJVideoAd": true,
        //     "isShowGDTInterstitialAd": false,
        //     "isShowCSJInterstitialAd": false,
        //     "isShowCSJAd": true,
        //     "isShowGDTAd": true,
        //     "videoAdIntervalTime": 300
        // })

        // console.log({
        //     gDTAppId: '1105344611',
        //     gDTInterstitialAdId: '1050652855580392',
        //     gDTVideoAdId: '8020744212936426',
        //     cSJAppId: '5446504',
        //     cSJVideoAdId: '102525233',
        //     cSJInterstitialAdId: '102525232',
        //     isShowGDTVideoAd: false,
        //     isShowCSJVideoAd: true,
        //     isShowGDTInterstitialAd: false,
        //     isShowCSJInterstitialAd: false,
        //     isShowCSJAd: true,
        //     isShowGDTAd: true,
        //     videoAdIntervalTime: 300
        // });

    }, [])
    const fetchData = () => {
        
        global.fetchCount = 0
        // console.warn("fetchData",birthTime+sex+name+birthPlace);
        let msc = null
        if (!name || name == "") {
            msc = "请输入姓氏"

        } else if (!sex || sex == "") {
            msc = "请输入性别"
        } else if (!birthTime || birthTime == "") {
            msc = "请输入出生日期"
        } else if (!birthPlace || birthPlace == "") {
            msc = "请输入出生地址"
        }
        if (msc) {
            this.showMsc(msc)
            return
        }

        props.navigation.navigate("NameList", { x: name, xb: sex, csrq: birthTime, csdd: birthPlace, zs: isDoubleWord ? 3 : 2 })

    }
    showMsc = (msc) => {
        Alert.alert(
            "提示",
            msc,
            [

                {
                    text: "确定"
                },
            ],
        )
    }

    const showDatePicker = () => {
        setDatePickerVisibility(true);
        birthDayRef.current.blur()
    };

    const hideDatePicker = () => {
        setDatePickerVisibility(false);

    };
    const showTimePicker = () => {
        setTimePickerVisibility(true);
        birthDayRef.current.blur()
    };

    const hideTimePicker = () => {
        setTimePickerVisibility(false);
    };
    const handleTimeConfirm = (date) => {

        setBirthDay(getBirthTime(date))
        // new Intl(DateTimeFormat, date)
        hideTimePicker();
    };

    const handleConfirm = (date) => {

        // console.warn("A date has been picked: ", date);

        const formatter = new Intl.DateTimeFormat('zh-CN', {
            dateStyle: 'short',
            timeZone: 'Asia/Shanghai'
        }).format(date)

        setBirthDay(getBirthDate(date))
        hideDatePicker();

    };
    const getNowTime = (date) => {

        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const date1 = date.getDate();
        const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        // const second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // const milliSeconds = date.getMilliseconds();
        let currentTime = year + '-' + month + '-' + date1 + ' ' + hour + ':' + minute;

        return currentTime;
    }
    const getBirthDate = (date) => {

        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const date1 = date.getDate();
        const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        // const second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // const milliSeconds = date.getMilliseconds();
        setBirthDate(year + '年' + month + '月' + date1 + '日')
        setBirthTime(year + '年' + month + '月' + date1 + '日')
        const birthDate = year + '年' + month + '月' + date1 + '日 ' + hour + '点' + minute + '分';

        return birthDate;
    }
    const getBirthTime = (date) => {

        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const date1 = date.getDate();
        const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        // const second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // const milliSeconds = date.getMilliseconds();
        const birthTime = birthDate + ' ' + hour + '点' + minute + '分';
        setBirthTime(birthTime)
        return birthTime;
    }


    return (
        <>
            <ImageBackground style={{ flex: 1, opacity: 0.2, position: 'absolute', width: '100%', height: '100%' }} source={require('../../img/b3.jpg')}>

            </ImageBackground>
            <ScrollView style={{ backgroundColor: 'translate' }}>
                <DateTimePickerModal
                    locale="zh-Hans"
                    display="inline"
                    isVisible={isDatePickerVisible}
                    mode="date"
                    onConfirm={handleConfirm}
                    onCancel={hideDatePicker}
                    cancelTextIOS="取消"
                    confirmTextIOS="确认"

                />
                <DateTimePickerModal
                    locale="zh-Hans"
                    display="spinner"
                    isVisible={isTimePickerVisible}
                    mode="time"
                    onConfirm={handleTimeConfirm}
                    onCancel={hideTimePicker}
                    cancelTextIOS="取消"
                    confirmTextIOS="确认"

                />
                <View style={{ justifyContent: 'center', alignItems: 'center', width: '100%', marginTop: mTop, marginBottom: 14 }}>
                    <Image style={{ width: artImgWidth, height: artImgHeight }} source={require('../../img/art7.png')} />
                </View>
                <View style={{
                    width: width / 10 * 8,
                    // backgroundColor: '#eee',
                    // borderWidth: 1,
                    justifyContent: 'center',
                    alignItems: 'center',
                    alignSelf: 'center',
                    padding: 10
                }}>
                    <TextInput
                        // autoFocus={true}
                        style={{
                            backgroundColor: "#fafafa",
                            margin: 8,
                            marginHorizontal: 10,
                            borderRadius: 20,
                            // flex: 1,
                            height: 45,
                            width: '100%',
                            borderColor: '#ddd',
                            paddingHorizontal: 20,
                            alignItems: 'center',
                            alignContent: 'center'
                        }}
                        placeholder={'姓氏'}
                        placeholderTextColor="#ddd"
                        // clearTextOnFocus={true}
                        onChangeText={setName}
                        clearButtonMode="while-editing"
                        returnKeyType='next'

                    // value={this.state.url}
                    />
                    <View style={{
                        width: '100%', height: 45, backgroundColor: "#fafafa", margin: 8,
                        marginHorizontal: 10,

                        borderRadius: 20,
                    }}>
                        <TextInput
                            ref={birthDayRef}
                            editable={true}
                            // autoFocus={true}
                            style={{
                                paddingHorizontal: 20,
                                // flex: 1,
                                height: 45,
                                // width: '100%',
                                borderColor: '#ddd',

                                alignItems: 'center',
                                alignContent: 'center'
                            }}
                            // onFocus={() => {
                            //     showDatePicker()
                            // }}
                            placeholder={'出生日期(阳历)'}
                            placeholderTextColor="#ddd"
                            clearTextOnFocus={true}
                            clearButtonMode="while-editing"
                            returnKeyType='next'

                            value={birthDay ? birthDay : null}
                        />
                        <View style={{ paddingHorizontal: 20, flexDirection: 'row', justifyContent: 'center', position: 'absolute', right: 0, top: 0, bottom: 0, alignContent: 'center', alignItems: 'center' }}>
                            <TouchableOpacity
                                onPress={() => {
                                    showDatePicker()
                                }}
                                style={{ marginEnd: 10 }}>
                                <Text style={{ color: 'tomato' }}>日期</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                onPress={() => {
                                    showTimePicker()
                                }}
                            >
                                <Text style={{ color: 'tomato' }}>时间</Text>
                            </TouchableOpacity>
                        </View>

                    </View>
                    <TextInput
                        // autoFocus={true}
                        style={{
                            backgroundColor: "#fafafa",
                            margin: 8,
                            marginHorizontal: 10,
                            borderRadius: 20,
                            // flex: 1,
                            height: 45,
                            width: '100%',
                            borderColor: '#ddd',
                            paddingHorizontal: 20,
                            alignItems: 'center',
                            alignContent: 'center'
                        }}
                        onChangeText={setBirthPlace}
                        placeholder={'出生城市（市或县）'}
                        placeholderTextColor="#ddd"
                        // clearTextOnFocus={true}
                        clearButtonMode="while-editing"
                        returnKeyType='next'

                    // value={this.state.url}
                    />
                    {isMore ? <>


                        <TextInput
                            // autoFocus={true}
                            style={{
                                backgroundColor: "#fafafa",
                                margin: 8,
                                marginHorizontal: 10,
                                borderRadius: 20,
                                // flex: 1,
                                height: 45,
                                width: '100%',
                                borderColor: '#ddd',
                                paddingHorizontal: 20,
                                alignItems: 'center',
                                alignContent: 'center'
                            }}
                            placeholder={'父亲姓名'}
                            placeholderTextColor="#ddd"
                            // clearTextOnFocus={true}
                            clearButtonMode="while-editing"
                            returnKeyType='next'

                        // value={this.state.url}
                        />
                        <TextInput
                            // autoFocus={true}
                            style={{
                                backgroundColor: "#fafafa",
                                margin: 8,
                                marginHorizontal: 10,
                                borderRadius: 20,
                                // flex: 1,
                                height: 45,
                                width: '100%',
                                borderColor: '#ddd',
                                paddingHorizontal: 20,
                                alignItems: 'center',
                                alignContent: 'center'
                            }}
                            placeholder={'父亲生日（阳历）'}
                            placeholderTextColor="#ddd"
                            // clearTextOnFocus={true}
                            clearButtonMode="while-editing"
                            returnKeyType='next'

                        // value={this.state.url}
                        />

                        <TextInput
                            // autoFocus={true}
                            style={{
                                backgroundColor: "#fafafa",
                                margin: 8,
                                marginHorizontal: 10,
                                borderRadius: 20,
                                // flex: 1,
                                height: 45,
                                width: '100%',
                                borderColor: '#ddd',
                                paddingHorizontal: 20,
                                alignItems: 'center',
                                alignContent: 'center'
                            }}
                            placeholder={'母亲姓名'}
                            placeholderTextColor="#ddd"
                            // clearTextOnFocus={true}
                            clearButtonMode="while-editing"
                            returnKeyType='next'

                        // value={this.state.url}
                        />
                        <TextInput
                            // autoFocus={true}
                            style={{
                                backgroundColor: "#fafafa",
                                margin: 8,
                                marginHorizontal: 10,
                                borderRadius: 20,
                                // flex: 1,
                                height: 45,
                                width: '100%',
                                borderColor: '#ddd',
                                paddingHorizontal: 20,
                                alignItems: 'center',
                                alignContent: 'center'
                            }}
                            placeholder={'母亲生日（阳历）'}
                            placeholderTextColor="#ddd"
                            // clearTextOnFocus={true}
                            clearButtonMode="while-editing"
                            returnKeyType='next'

                        // value={this.state.url}
                        />

                    </> : null}

                    <SwitchButton setSex={setSex} />
                    <NameWordCountButton setIsDoubleWord={setIsDoubleWord} />

                    <View style={{
                        backgroundColor: "#fafafa",
                        margin: 20,
                        marginHorizontal: 10,
                        borderRadius: 20,
                        // flex: 1,
                        height: 45,
                        width: '100%',
                        borderColor: '#ddd',
                        //   padding:20,
                        alignItems: 'center',
                        alignContent: 'center',
                        flexDirection: 'row',
                        overflow: 'hidden'
                    }}>
                        <TouchableOpacity
                            onPress={() => {
                                if(AppConfig.isFirstOpenApp){
                                    Alert.alert('提示',
                                    '提示内容：“尊敬的用户您好，本软件使用完全免费，但大数据分析及智能测算会产生成本，所以起名时会有一段视频广告，如果您同意请点击是，广告结束后即可获取宝宝的姓名。（本提示仅第一次出现）',
                                    [{
                                        text: "取消", onPress: () => {
                        
                                        }
                                    },
                                        {
                                            text: "获取名字", onPress: () => {
                                                AppConfig.isFirstOpenApp = false
                                                saveAppConfig(AppConfig)
                                                fetchData()
                        
                                            }
                                        },
                                    ],
                                    )
                                }else{
                                    fetchData()
                        
                                }
                                
                                // setIsDoubleWord(true)
                            }}
                            style={[{
                                height: 45, width: '100%', alignItems: 'center',
                                justifyContent: 'center',
                                backgroundColor: 'crimson'
                            },]}>
                            <Text style={[{ color: '#fff', fontSize: 20, fontWeight: 'bold' }]}>起名</Text>
                        </TouchableOpacity>


                    </View>
                    <Text onPress={() => {
                        setIsMore(!isMore)
                    }} style={{ color: 'crimson', alignSelf: 'flex-start' }}>可选项</Text>

                </View>

            </ScrollView>
        </>
    )
}

const SwitchButton = (props) => {
    const [isBoy, setIsBoy] = useState(true)
    return (
        <View style={{
            backgroundColor: "#fafafa",
            margin: 8,
            marginHorizontal: 10,
            borderRadius: 20,
            // flex: 1,
            height: 45,
            width: '100%',
            borderColor: '#ddd',
            //   padding:20,
            alignItems: 'center',
            alignContent: 'center',
            flexDirection: 'row',
            overflow: 'hidden'
        }}>
            <TouchableOpacity
                onPress={() => {
                    setIsBoy(true)
                    props.setSex('男')
                }}
                style={[{
                    height: 45, width: '50%', alignItems: 'center',
                    justifyContent: 'center',
                }, isBoy ? { backgroundColor: 'crimson' } : {}]}>
                <Text style={[{}, isBoy ? { color: '#fff' } : { color: '#000' }]}>男孩</Text>
            </TouchableOpacity>
            <TouchableOpacity
                onPress={() => {
                    setIsBoy(false)
                    props.setSex('女')
                }} style={[{
                    height: 45, width: '50%', alignItems: 'center',
                    justifyContent: 'center',
                }, isBoy ? {} : { backgroundColor: 'crimson' }]}>
                <Text style={[{}, isBoy ? { color: '#000' } : { color: '#fff' }]}>女孩</Text>
            </TouchableOpacity>
        </View>
    )
}
const NameWordCountButton = (props) => {
    const [isDoubleWord, setIsDoubleWord] = useState(true)
    return (
        <View style={{
            backgroundColor: "#fafafa",
            margin: 8,
            marginHorizontal: 10,
            borderRadius: 20,
            // flex: 1,
            height: 45,
            width: '100%',
            borderColor: '#ddd',
            //   padding:20,
            alignItems: 'center',
            alignContent: 'center',
            flexDirection: 'row',
            overflow: 'hidden'
        }}>
            <TouchableOpacity
                onPress={() => {
                    setIsDoubleWord(true)
                    props.setIsDoubleWord(true)
                }}
                style={[{
                    height: 45, width: '50%', alignItems: 'center',
                    justifyContent: 'center',
                }, isDoubleWord ? { backgroundColor: 'crimson' } : {}]}>
                <Text style={[{}, isDoubleWord ? { color: '#fff' } : { color: '#000' }]}>双字名</Text>
            </TouchableOpacity>
            <TouchableOpacity
                onPress={() => {
                    setIsDoubleWord(false)
                    props.setIsDoubleWord(false)
                }} style={[{
                    height: 45, width: '50%', alignItems: 'center',
                    justifyContent: 'center',
                }, isDoubleWord ? {} : { backgroundColor: 'crimson' }]}>
                <Text style={[{}, isDoubleWord ? { color: '#000' } : { color: '#fff' }]}>单字名</Text>
            </TouchableOpacity>
        </View>
    )
}
const BirthDateButton = (props) => {
    const [isBoy, setIsBoy] = useState(true)
    return (
        <View style={{
            backgroundColor: "#fafafa",
            margin: 8,
            marginHorizontal: 10,
            borderRadius: 20,
            // flex: 1,
            height: 45,
            width: '100%',
            borderColor: '#ddd',
            //   padding:20,
            alignItems: 'center',
            alignContent: 'center',
            flexDirection: 'row',
            overflow: 'hidden'
        }}>
            <TouchableOpacity
                onPress={() => {
                    setIsBoy(true)
                }}
                style={[{
                    height: 45, width: '50%', alignItems: 'center',
                    justifyContent: 'center',
                }, isBoy ? { backgroundColor: 'crimson' } : {}]}>
                <Text style={[{}, isBoy ? { color: '#fff' } : { color: '#000' }]}>男孩</Text>
            </TouchableOpacity>
            <TouchableOpacity
                onPress={() => {
                    setIsBoy(false)
                }} style={[{
                    height: 45, width: '50%', alignItems: 'center',
                    justifyContent: 'center',
                }, isBoy ? {} : { backgroundColor: 'crimson' }]}>
                <Text style={[{}, isBoy ? { color: '#000' } : { color: '#fff' }]}>女孩</Text>
            </TouchableOpacity>
        </View>
    )
}